﻿using AutoMapper;
using B.S.BasicData.Api.Write.Applications.Commands.Accounts;
using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastcuture.Commons;
using B.S.BasicData.Infrastcuture.Interfaces;
using MediatR;
using NLog.LayoutRenderers.Wrappers;
using System.Transactions;
using Yitter.IdGenerator;

namespace B.S.BasicData.Api.Write.Applications.CommandHandlers.Accounts
{
    public class UpdateQueryCommandHandler : IRequestHandler<UpdateQueryCommand, ApiResult<object>>
    {
        private readonly IBaseRepository<UserInfo> baseRepository;
        private readonly IBaseRepository<NlogInfo> baseRepository1;
        private readonly IMapper mapper;

        public UpdateQueryCommandHandler(IBaseRepository<UserInfo> baseRepository, IMapper mapper, IBaseRepository<NlogInfo> baseRepository1)
        {
            this.baseRepository = baseRepository;
            this.mapper = mapper;
            this.baseRepository1 = baseRepository1;
        }

        public async Task<ApiResult<object>> Handle(UpdateQueryCommand request, CancellationToken cancellationToken)
        {
            ApiResult<object> result =new ApiResult<object>();
            result.Code = ResultCode.UpdateSuccess;
            result.Message = ResultCode.UpdateSuccess.Description();
            //开始事务
            using(var tran=new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {

                    UserInfo user = mapper.Map<UserInfo>(request);
                    await baseRepository.Update(user);
                    NlogInfo nlog = new NlogInfo();
                    nlog.NlogId = YitIdHelper.NextId();
                    nlog.NlogName = "修改操作";
                    nlog.NlogTime = DateTime.Now;
                    nlog.Context = $"修改了一条名称为{request.UserName}的操作";
                    await baseRepository1.Add(nlog);
                    //提交事务
                    tran.Complete();
                }
                catch (Exception)
                {

                    throw;
                }
                return await Task.FromResult(result);
            }
        }
    }
}
